package logic

import (
	"context"
	"github.com/pkg/errors"
	"zg2/zk1_user/userRpc/models"
	"zg2/zk1_user/userRpc/pkg"

	"zg2/zk1_user/userRpc/internal/svc"
	"zg2/zk1_user/userRpc/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type AuthRealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAuthRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuthRealNameLogic {
	return &AuthRealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AuthRealNameLogic) AuthRealName(in *user.AuthRealNameRequest) (*user.AuthRealNameResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var ur models.UserIdentity
	ur.UserId = in.UserId

	if err = ur.GetRealNameByUserId(); err != nil {
		logx.Error("用户信息获取失败")
		return nil, errors.New("用户信息获取失败")
	}

	if ur.ID != 0 {
		logx.Error("用户已实名")
		return nil, errors.New("用户已实名")
	}

	if !pkg.AuThRealName(in.IdCard, in.RealName) {
		logx.Error("实名失败：调用第三方实名认证接口")
		return nil, errors.New("实名失败")
	}

	ur.RealName = in.RealName
	ur.IdCard = pkg.Md5(in.IdCard)

	if err = ur.CreateAuth(); err != nil {
		logx.Error("用户实名失败")
		return nil, errors.New("用户实名失败")
	}

	return &user.AuthRealNameResponse{
		UserId: ur.UserId,
	}, nil
}
